package com.company.fastsbapi.service.impl;

import com.company.fastsbapi.dataobject.model.Person;
import com.company.fastsbapi.dataobject.ro.PersonAddRO;
import com.company.fastsbapi.dataobject.ro.PersonUpdateRO;
import com.company.fastsbapi.repository.PersonRepository;
import com.company.fastsbapi.service.PersonService;
import com.company.fastsbapi.enums.ResultEnum;
import com.company.fastsbapi.exception.ServiceException;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


/**
* Created by CodeGenerator on 2020/09/08.
*/
@Service
@Transactional
@Slf4j
public class PersonServiceImpl implements PersonService {

    @Autowired
    private PersonRepository personRepository;

    @Override
    public void addPerson(PersonAddRO personAddRO) {
        Person person = new Person();
        BeanUtils.copyProperties(personAddRO, person);
        personRepository.save(person);
    }

    @Override
    public void deletePerson(Integer id) {
        Person person = personRepository.getOne(id);
        if (person == null) {
            log.error("【deletePerson出错】id不存在,id:{}", id);
            throw new ServiceException(ResultEnum.ERROR_ID);
        }
        personRepository.delete(id);

    }

    @Override
    public void updatePerson(PersonUpdateRO personUpdateRO) {
        Person person = personRepository.findOne(personUpdateRO.getId());
        if (person == null) {
            log.error("【updatePerson出错】id不存在,id:{}", personUpdateRO.getId());
            throw new ServiceException(ResultEnum.ERROR_ID);
        }
        BeanUtils.copyProperties(personUpdateRO, person);
        personRepository.save(person);
    }

    @Override
    public Person findPerson(Integer id) {
        Person person = personRepository.findOne(id);
        if (person == null) {
            log.error("【findPerson出错】id不存在,id:{}", id);
            throw new ServiceException(ResultEnum.ERROR_ID);
        }
        return person;
    }

    @Override
    public Page<Person> findPersonPage(PageRequest pageRequest) {
        return personRepository.findAll(pageRequest);
    }

}